<template>
  <div class="workflow-editor-container">
    <el-card class="editor-card">
      <template #header>
        <div class="card-header">
          <div>
            <span class="editor-title">{{ isEditing ? '编辑流程模板' : '创建流程模板' }}</span>
          </div>
          <div>
            <el-button type="primary" @click="saveTemplate">保存模板</el-button>
            <el-button v-if="isEditing && template.status === 'draft'" type="success" @click="publishTemplate">发布模板</el-button>
          </div>
        </div>
      </template>
      
      <div class="template-form">
        <el-form :model="template" label-width="120px">
          <el-form-item label="模板名称" required>
            <el-input v-model="template.name" placeholder="请输入模板名称"></el-input>
          </el-form-item>
          <el-form-item label="模板描述">
            <el-input v-model="template.description" type="textarea" placeholder="请输入模板描述"></el-input>
          </el-form-item>
        </el-form>
      </div>
      
      <div class="editor-container">
        <BpmnEditor ref="bpmnEditor" :initialXml="template.bpmn_xml" @save="onBpmnSave" @error="onBpmnError" />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import BpmnEditor from '../components/BpmnEditor.vue';

const route = useRoute();
const router = useRouter();
const bpmnEditor = ref(null);

const template = ref({
  id: null,
  name: '',
  description: '',
  bpmn_xml: null,
  status: 'draft'
});

const isEditing = ref(false);

// 保存BPMN数据
const onBpmnSave = (xml) => {
  template.value.bpmn_xml = xml;
};

// BPMN编辑器错误处理
const onBpmnError = (error) => {
  ElMessage.error(`BPMN编辑器错误: ${error}`);
};

// 保存模板
const saveTemplate = async () => {
  try {
    if (!template.value.name) {
      return ElMessage.warning('请输入模板名称');
    }
    
    if (!template.value.bpmn_xml) {
      // 如果bpmn_xml为空，请求当前编辑器的XML
      if (bpmnEditor.value) {
        bpmnEditor.value.saveDiagram();
        return;
      } else {
        return ElMessage.warning('流程设计内容不能为空');
      }
    }
    
    if (isEditing.value) {
      // 更新现有模板
      await axios.put(`/workflow/templates/${template.value.id}`, {
        name: template.value.name,
        description: template.value.description,
        bpmn_xml: template.value.bpmn_xml
      });
      ElMessage.success('模板更新成功');
    } else {
      // 创建新模板
      const response = await axios.post('/workflow/templates', {
        name: template.value.name,
        description: template.value.description,
        bpmn_xml: template.value.bpmn_xml
      });
      template.value.id = response.data.template_id;
      isEditing.value = true;
      ElMessage.success('模板创建成功');
      
      // 更新URL，不刷新页面
      router.replace(`/workflow-editor/${template.value.id}`);
    }
  } catch (error) {
    console.error('保存模板失败:', error);
    // 打印完整的错误响应
    if (error.response) {
      console.error('错误状态码:', error.response.status);
      console.error('错误信息:', error.response.data);
    }
    ElMessage.error(`保存模板失败: ${error.response?.data?.message || error.message || '未知错误'}`);
  }
};

// 发布模板
const publishTemplate = async () => {
  try {
    if (!template.value.id) {
      return ElMessage.warning('请先保存模板');
    }
    
    // 确认发布
    await ElMessageBox.confirm(
      '发布后将不能修改模板，如需更改将创建新版本。确定要发布此模板吗？',
      '发布确认',
      {
        confirmButtonText: '确定发布',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    await axios.post(`/workflow/templates/${template.value.id}/publish`);
    template.value.status = 'published';
    ElMessage.success('模板发布成功');
  } catch (error) {
    if (error !== 'cancel') {
      console.error('发布模板失败:', error);
      ElMessage.error(`发布模板失败: ${error.response?.data?.message || '未知错误'}`);
    }
  }
};

// 加载模板数据
const loadTemplate = async (templateId) => {
  try {
    const response = await axios.get(`/workflow/templates/${templateId}`);
    template.value = response.data;
    isEditing.value = true;
  } catch (error) {
    console.error('加载模板失败:', error);
    ElMessage.error(`加载模板失败: ${error.response?.data?.message || '未知错误'}`);
    router.push('/workflow-templates');
  }
};

onMounted(() => {
  // 检查是否有templateId参数，有则加载模板
  const templateId = route.params.id;
  if (templateId) {
    loadTemplate(templateId);
  }
});
</script>

<style scoped>
.workflow-editor-container {
  padding: 20px;
}

.editor-card {
  margin-bottom: 20px;
}

.editor-title {
  font-size: 18px;
  font-weight: bold;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.template-form {
  margin-bottom: 20px;
}

.editor-container {
  height: 700px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}
</style> 